<template>
	<view>
		<scroll-view class="JSSegmentedControl" scroll-x="trues" @scroll="scroll">
			<view class="JSSegmentedControlItem" v-for="(item, index) in segmentedControlTitles" :key="index" @click="segmentControlDidSelected(index)">
				<view :class="[segmentedControlSelectedIndex == index ? 'JSSegmentedControlItemTitle-selected' : 'JSSegmentedControlItemTitle-normal']">{{item}}</view>
				<view :class="[segmentedControlSelectedIndex == index ? 'JSSegmentedControlItemLine lineSelected' : 'JSSegmentedControlItemLine lineNormal']"></view>
			</view>
		</scroll-view>
		<mescroll-uni class="scroll-view" :top="100" :down="downOption" @down="downCallback" :up="upOption" @up="upCallback"
		 @init="mescrollInit">
			<!-- <view> @down, @up 必须配置 </view> -->
			<!-- <view> :down, :up 可省略 </view> -->
			<view class="item-backgroundView" v-for="(item, index) in dataList" :key="index" @click="detail(index)">
				<view class="item-title-view">
					<view class="item-title util-font-medium">
						<view class="item-title-text">
							{{item.merProduct.name}}
						</view>
						<image class="item-title-image" src="../../static/mine/arrow-right.png" mode="aspectFit"></image>
					</view>
					<view v-if="item.status == 0" class="item-status util-font-medium">待支付</view>
					<view v-if="item.status == 1" class="item-status util-font-medium">未使用</view>
					<view v-if="item.status == 2" class="item-status util-font-medium">已完成</view>
					<view v-if="item.status == 3 && item.refundStatus == 0" class="item-status util-font-medium">未发生退款</view>
					<view v-if="item.status == 3 && item.refundStatus == 1" class="item-status util-font-medium">退款中</view>
					<view v-if="item.status == 3 && item.refundStatus == 2" class="item-status util-font-medium">已退款</view>
					<view v-if="item.status == 4" class="item-status util-font-medium">已取消</view>
				</view>
				<view class="item-info-view">
					<image class="item-info-image" src="https://tanmyan.oss-cn-zhangjiakou.aliyuncs.com/web/image3.png" mode="aspectFill"></image>
					<view class="item-info-content util-font-regular">
						<view class="item-info-number">数量：{{item.number}}</view>
						<view class="item-info-amount">总价：￥{{item.amount/100.}}</view>
						<view class="item-info-payment ">
							<text class="item-info-payment-price1">实付金额：</text>
							<text class="item-info-payment-price2">￥</text>
							<text class="item-info-payment-price3">{{item.payment/100.}}</text>
							<text v-if="item.type == 0 && item.shareUserAmount" class="price-brokerage">返佣{{item.shareUserAmount/100.0}}元</text>
						</view>
					</view>
				</view>
				<view class="order-button-view" @click.stop="blank">
					<!-- <view class="order-button" @click="pay(rowIndex)">立即支付</view> -->
					<!-- <view class="order-button2" @click="pay(rowIndex)">立即支付</view> -->
					<view v-if="item.status == 0" class="order-button" @click="pay(index)">立即支付</view>
					<!-- <view v-if="item.status == 0" class="order-button2" @click="cancel(index)">取消订单</view> -->
					<view v-if="item.status == 1" class="order-button" @click="toUse(index)">去使用</view>
					<view v-if="item.status == 2" class="order-button" @click="buyAgain(index)">再次购买</view>
					<view v-if="item.status == 2" class="order-button2" @click="deleteOrder(index)">删除订单</view>
					<view v-if="item.status == 3 && item.refundStatus == 1" class="order-button" @click="detail(index)">查看订单</view>
					<view v-if="item.status == 3 && item.refundStatus == 1" class="order-button2" @click="buyAgain(index)">再次购买</view>
					<view v-if="item.status == 3 && item.refundStatus == 2" class="order-button" @click="buyAgain(index)">再次购买</view>
					<view v-if="item.status == 3 && item.refundStatus == 2" class="order-button2" @click="deleteOrder(index)">删除订单</view>
					<view v-if="item.status == 4" class="order-button" @click="buyAgain(index)">再次购买</view>
					<view v-if="item.status == 4" class="order-button2" @click="deleteOrder(index)">删除订单</view>
				</view>
			</view>
		</mescroll-uni>
	</view>
</template>

<script>
	import MescrollUni from "@/components/mescroll-uni/mescroll-uni.vue";
	export default {
		components: {
			MescrollUni,
		},
		computed: {
			safeAreaInsetBottom() {
				return uni.upx2px(uni.getSystemInfoSync().safeAreaInsets.bottom * 2)
			},
			halfTop() {
				return uni.upx2px(30) + 'px'
			}
		},
		data() {
			return {
				segmentedControlTitles: ["全部订单", "待支付", "未使用", "已完成", "取消/退款"],
				segmentedControlSelectedIndex: 0,

				// 列表数据
				mescroll: null, // mescroll的实例化对象
				dataList: [],

				// 下拉刷新的常用配置
				downOption: {
					use: true, // 是否启用下拉刷新; 默认true
					auto: false, // 是否在初始化完毕之后自动执行下拉刷新的回调; 默认true
				},
				// 上拉加载的常用配置
				upOption: {
					use: true, // 是否启用上拉加载; 默认true
					auto: false, // 是否在初始化完毕之后自动执行上拉加载的回调; 默认true
					page: {
						num: 0,
						size: 10
					},
					toTop: {
						safearea: true
					},
					noMoreSize: 5, // 配置列表的总数量要大于等于5条才显示'-- END --'的提示
					empty: {
						tip: '暂无相关数据'
					},
					// bgColor: '#FF0000'
				},
			}
		},
		onLoad(options) {
			var that = this
			// uni.$off("orderListRefresh")
			
			this.segmentControlDidSelected(options.selectIndex)
			
			uni.$on("orderListRefresh", function(data){
				
				console.log('*****************')
				
				for (var i = 0; i < that.dataList.length; i++) {
					var item = that.dataList[i]
					
					console.log("for循环" + i)
					
					if (item.id == data.id) {
						console.log("判断1")
						if (item.status != data.status) {
							console.log("判断2")
							if (that.segmentedControlSelectedIndex == 0) {
								console.log("判断3")
								that.dataList.splice(i, 1, data)
							}else{
								that.dataList.splice(i, 1)
								console.log("判断4")
							}
						}else{
							that.dataList.splice(i, 1, data)
							console.log("判断5")
						}
						return
					}else{
						continue
					}
				}
			})
			
		},
		methods: {
			segmentControlDidSelected: function(index) {
				this.segmentedControlSelectedIndex = index
				this.mescroll.resetUpScroll() // 刷新列表数据
			},

			// mescroll组件初始化的回调,可获取到mescroll对象
			mescrollInit(mescroll) {
				this.mescroll = mescroll;
			},
			/*下拉刷新的回调 */
			downCallback(mescroll) {
				console.log("下拉刷新")
				// 这里加载你想下拉刷新的数据, 比如刷新轮播数据
				// loadSwiper();
				// 下拉刷新的回调,默认重置上拉加载列表为第一页 (自动执行 mescroll.num=1, 再触发upCallback方法 )
				mescroll.resetUpScroll()
			},
			/*上拉加载的回调: mescroll携带page的参数, 其中num:当前页 从1开始, size:每页数据条数,默认10 */
			upCallback(mescroll) {
				console.log("上拉加载更多")
				this.loadData()
			},

			loadData: function() {

				var that = this
				var data = new Object()
				data.page = that.mescroll.num
				data.limit = that.mescroll.size
				data.userId = uni.getStorageSync('userInfo').id
				data.orderByField = 'create_time'
				data.isAsc = false
				if (that.segmentedControlSelectedIndex == 1) {
					data.status = '0'
				} else if (that.segmentedControlSelectedIndex == 2) {
					data.status = '1'
				} else if (that.segmentedControlSelectedIndex == 3) {
					data.status = '2'
				} else if (that.segmentedControlSelectedIndex == 4) {
					data.status = '3,4'
				}

				that.sendRequest({
					url: 'app/ordOrders/page',
					header: that.$urlRequest.getHeader('token'),
					method: 'POST',
					data: data,
					success: function(res) {
						console.log(res)

						let currentPageData = res.data.records
						let totalPage = res.data.pages

						if (that.mescroll.num == 1) {
							that.dataList = []
						}
						that.dataList = that.dataList.concat(currentPageData)

						that.$nextTick(function() {
							that.mescroll.endByPage(currentPageData.length, totalPage)
						})
					}
				})
			},

			// 占位方法,防止事件穿透
			blank: function() {

			},
			// 立即支付
			pay: function(index) {
				var that = this
				var orderId = (that.dataList[index]).id
				that.sendRequest({
					url: 'app/ordOrders/toWxpay/' + orderId,
					method: 'POST',
					header: that.$urlRequest.getHeader('token'),
					success: function(wxres) {
						console.log(wxres)

						uni.requestPayment({
							provider: 'wxpay',
							timeStamp: wxres.data.data.timeStamp,
							nonceStr: wxres.data.data.nonceStr,
							package: wxres.data.data.packageValue,
							signType: wxres.data.data.signType,
							paySign: wxres.data.data.paySign,
							success: function(payres) {
								uni.showToast({
									title: '支付成功',
									mask: true,
									duration: 1000
								})
								// 更新列表数据
								var newItem = that.dataList[index]
								newItem.status = 1
								if (that.segmentedControlSelectedIndex == 0) {
									that.dataList.splice(index, 1, newItem)
								}else{
									that.dataList.splice(index, 1)
								}

								// 跳转
								setTimeout(function() {
									uni.navigateTo({
										url: 'detail?id=' + orderId
									})
								}, 1000)
							},
							fail: function(err) {
								if (err.errMsg.requestPayment == 'fail cancel') {
									uni.showToast({
										title: '用户取消了支付',
										icon: 'none',
										duration: 1000
									})
								} else {
									uni.showToast({
										title: err.errMsg.requestPayment,
										duration: 1000,
										icon: 'none'
									})
								}
							}
						})
					}
				})
			},
			// 取消订单
			cancel: function(index) {
				var that = this
				var orderId = (that.dataList[index]).id

				uni.showModal({
					title: '取消订单',
					content: '这可能是最低价格，取消之后此订单不可恢复，确定取消？',
					showCancel: true,
					confirmText: '再等等',
					confirmColor: '#FF0000',
					cancelText: '取消订单',
					success(res) {
						if (res.cancel) {
							that.sendRequest({
								url: 'app/ordOrders/cancle/' + orderId,
								method: 'POST',
								header: that.$urlRequest.getHeader('token'),
								success: res => {
									uni.showToast({
										title: '订单已取消',
										mask: true,
										duration: 1000
									})
									// 更新列表数据
									var newItem = that.dataList[index]
									newItem.status = 4
									if (that.segmentedControlSelectedIndex == 1) {
										that.dataList.splice(index, 1)
									}else{
										that.dataList.splice(index, 1, newItem)
									}
				
									// 跳转
									setTimeout(function() {
										uni.navigateTo({
											url: 'detail?id=' + orderId
										})
									}, 1000)
								}
							})
						}
					}
				});
			},
			toUse: function(index){
				var that = this
				uni.navigateTo({
					url: 'detail?id=' + (that.dataList[index]).id
				})
			},
			// 再次购买
			buyAgain: function(index) {
				var that = this
				uni.navigateTo({
					url: '../index/detail?pid=' + (that.dataList[index]).merProduct.id
				})
			},
			// 查看订单
			detail: function(index) {
				var item = this.dataList[index]
				uni.navigateTo({
					url: 'detail?id=' + item.id
				})
			},
			// 删除订单
			deleteOrder: function(index) {
				var that = this
				var orderId = (that.dataList[index]).id
				uni.showModal({
					title: '确认删除',
					content: '删除的订单将无法恢复',
					confirmText: '再看看',
					cancelText: '确认删除',
					confirmColor: '#FF0000',
					showCancel: true,
					success: (res) => {
						if (res.cancel) {
							that.sendRequest({
								url: 'app/ordOrders/delete/' + orderId,
								method: 'POST',
								header: that.$urlRequest.getHeader('token'),
								success: (res) => {
									uni.showToast({
										title: '订单已删除',
										duration: 1000
									})

									// 更新列表数据
									that.dataList.splice(index, 1)
								}
							})
						}
					}
				});
			}
		}
	}
</script>

<style>
	page {
		background-color: #eeeeee;
	}

	.JSSegmentedControl {
		z-index: 9990;
		position: fixed;
		/* css变量 */
		top: 0;
		left: 0;
		width: 100%;
		height: 100upx;
		background-color: white;
		white-space: nowrap;
	}
	
	.JSSegmentedControl ::-webkit-scrollbar {
	   width: 0;
	   height: 0;
	   color: transparent;
	}

	.JSSegmentedControlItem {
		display: inline-block;
		width: 145upx;
		height: 100upx;
		text-align: center;
		white-space: nowrap;
	}

	.JSSegmentedControlItemTitle-normal {
		font-size: 30upx;
		font-family: 'PingFangSC-Regular';
		/* color: rgba(255, 255, 255, 0.6); */
		color: #333333;
		margin-top: 30upx;
	}

	.JSSegmentedControlItemTitle-selected {
		font-size: 30upx;
		font-family: 'PingFangSC-Medium';
		color: #F19216;
		margin-top: 30upx;
	}

	.JSSegmentedControlItemLine {
		width: 60upx;
		height: 10upx;
		border-radius: 5upx;
		margin: 0 auto;
		margin-top: 15upx;
		background-color: #F19216;
	}

	.lineSelected {
		opacity: 1.0;
	}

	.lineNormal {
		opacity: 0.0;
	}

	/* 商品详情 */
	.scroll-view {
		background-color: #F5F5F5;
	}

	.item-backgroundView {
		width: 710upx;
		margin: 20upx 15upx;
		padding: 0 30upx;
		box-sizing: border-box;
		background-color: white;
		border-radius: 15upx;
		position: relative;
	}

	.item-title-view {
		width: 100%;
		height: 80upx;
	}
	.item-title {
		width: 550upx;
		height: 80upx;
		line-height: 80upx;
		float: left;
	}
	.item-title-text {
		width: 500upx;
		height: 80upx;
		line-height: 80upx;
		color: #333333;
		font-size: 32upx;
		white-space: nowrap;
		text-overflow: ellipsis;
		overflow: hidden;
		word-break: break-all;
		float: left;
	}
	.item-title-image {
		width: 30upx;
		height: 17upx;
		margin-top: 30upx;
		float: left;
	}
	.item-status {
		color: #ea6431;
		font-size: 28upx;
		width: 100upx;
		height: 80upx;
		line-height: 80upx;
		text-align: right;
		float: right;
	}

	.item-info-view {
		width: 100%;
		height: 120upx;
		overflow: hidden;
		padding-bottom: 30upx;
		border-bottom: 2upx solid #F1F1F1;
	}

	.item-info-image {
		width: 120upx;
		height: 120upx;
		float: left;
		border-radius: 10upx;
	}

	.item-info-content {
		width: 500upx;
		height: 120upx;
		margin-left: 30upx;
		float: left;
	}

	.item-info-number {
		color: #999999;
		font-size: 26upx;
		height: 34upx;
		line-height: 34upx;
	}

	.item-info-amount {
		color: #999999;
		font-size: 26upx;
		height: 36upx;
		line-height: 36upx;
	}

	.item-info-payment {
		height: 50upx;
		line-height: 50upx;
	}
	.item-info-payment-price1 {
		color: #666666;
		font-size: 28upx;
	}
	.item-info-payment-price2 {
		color: #ea6431;
		font-size: 20upx;
	}
	.item-info-payment-price3 {
		color: #ea6431;
		font-size: 36upx;
	}
	.price-brokerage {
		padding: 0upx 8upx 0upx;
		background-color: #ec6e2d;
		height: 30upx;
		line-height: 30upx;
		border-radius: 6upx;
		color: #FFFFFF;
		font-size: 20upx;
		margin-left: 10rpx;
		position: relative;
		top: -5rpx;
	}

	.order-button-view {
		pointer-events: auto;
		width: 100%;
		height: 64upx;
		padding: 23upx 0;
	}

	.order-button {
		width: 175upx;
		height: 64upx;
		line-height: 64upx;
		color: #FFFFFF;
		font-size: 29upx;
		text-align: center;
		border-radius: 32upx;
		background: linear-gradient(to right, #eb8735, #ea6431);
		float: right;
		margin-left: 30upx;
		font-family: "PingFangSC-regular";
	}
	.order-button2 {
		width: 175upx;
		height: 64upx;
		line-height: 64upx;
		color: #ea6431;
		font-size: 29upx;
		text-align: center;
		border-radius: 32upx;
		float: right;
		border: 2upx solid #ea6431;
		margin-left: 30upx;
		font-family: "PingFangSC-regular";
	}
</style>
